/**
 * 服务启动
 */

import './utils/global.js';

import Fastify from 'fastify';

const fastify = Fastify({
  logger: false
});

import mongodb from './plugins/mongodb/mongodb.js';
import magicApi from './plugins/magic-api.js';

// runer
fastify.register(async (fastify) => {
  // mongodb
  await fastify.register(mongodb, {
    // name: 'mongo01',
    // url: 'mongodb+srv://[username:password@]host[/[defaultauthdb][?options]]',
    // url: 'mongodb://20.30.1.120:27999/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.10.1',
    url: 'mongodb://box.zhizhuwang.online:8018/lite-cms',
    // url: 'mongodb://47.100.9.3:8018/lite-cms',
    forceClose: true, // app closed with db disconnected.
  });

  // fastify.addHook('preHandler', (req, reply, next) => {
  //   console.log('??????', req.method, req.url);
  //   next();
  // });
  
  // magic
  // await fastify.register(async fastify => {
  //   // 内容管理的基础，sys-*、member
  //   await fastify.register(magicApi, { code_path: 'magic-cms' });
  //   // magic-post 咨询
  //   await fastify.register(magicApi, { code_path: 'magic-post' });
  //   // magic-admin
  // }, { prefix: '/api' });

  // 资讯
  // await fastify.register(magicApi, {
  //   prefix: '/wp-json/jiangqie/v1',
  //   code_path: 'magic-information',
  // });

  // admin + web
  await fastify.register(magicApi, {
    prefix: '/admin',
    code_path: 'magic-admin',
  });

  // Server拦截所有请求
  fastify.all('*', async (req, reply) => {
    return {
      code: 404,
      msg: 'Not Found Function To Run.',
      data: null,
    };
  });
});

// Run the server!
fastify.listen({
  port: 3000,
  // host: '127.0.0.1',
  host: '0.0.0.0',
}, (err, address) => {
  if (err) {
    console.error(err);
    process.exit(1);
  }
  console.log(`Server now listening on ${address}`);
});
